/*
 * @Description:移料
 * @Author: bfn
 * @Date: 2019-12-9
 * @LastEditors: ezio
 * @LastEditTime: 2020-09-14 13:58:01
 */
import itemTypeDialog from '@/components/biz/extend/Dialog/itemTypeDialog.vue';
import { calcIndexTableHeightMixins } from '@/mixin/calcIndexTableHeightMixins';
import { getEnum } from '@/model/api/main/basic/public';
import {
  checkAvailable,
  findMaterialList,
  findPeople,
  getBySelection,
  getDefaultType,
  getDeptList,
  getNewQty,
  getPrintParam,
  getSn,
  // getTemList,
  initPage,
  saveInfo,
  submitInfo,
  getInfoByTypeCode,
  // lotInfoApi,
  htWmsGetDataByBarcode,
  findHtWmsLineStock,
  findMoveWmsListbyOrder,
  getHtWmsHouseList
} from '@/model/api/main/extend/moveMaterialHtModule';
import { getPrintInfo } from '@/model/api/main/extend/receiveModule';
import { print } from '@/utils/print';
import uuid from '@/utils/uuid';
import printDialog from '@/views/main/extend/receiveModule/childrenModule/receiveInfoModule/printDialog.vue';
import { Decimal } from 'decimal.js';
import $ from 'jquery';
import _ from 'lodash';
import applicantPerson from '@/views/main/extend/moveMaterialHtModule/childrenModule/moveInfoHtModule/applicantPerson.vue';
import BtnWrapper from '@/components/ui/btnWrapper/index.vue';
import { getOrderBOM} from '@/model/api/main/extend/htVouchApplyModule';
export default {
  name: 'moveInfoHtModule',
  mixins: [calcIndexTableHeightMixins],
  components: {
    itemTypeDialog,
    printDialog,
    applicantPerson,
    BtnWrapper,
  },
  subscriptions() {
    return {
      account: window.Vm.accountVm.getStream(),
    };
  },
  data() {
    return {
      loadingTree: false,
      factoryArr: [], // 车间下拉框
      locationTypeArr: [], // 目标位置类型下拉框
      targetLocationList: [], // 目标位置下拉框
      formLocationTypeArr: [], // 弹框中位置类型下拉框
      formLocationArr: [], // 弹框位置下拉框
      locationId: '',
      locationCode: '',
      dialogShow: false,
      // 位置编码
      locationName: '',
      // 位置名称
      prodorgCode: '', // 车间编号,
      prodorgName: '', // 车间名称,
      // 基础参数
      basicInfo: {
        orderNo: '',
        officeId: '',
        materialBarcode: '',
        relateduserName: '',
        relateduserId: '',
        relateduserCode: '',
        activityTime: new Date(),
        batchNo: '',
        mtlKind: '',
        locationId: '',
        locationKind: '',
        // 新增
        deptId: '',
        deptCode: '',
        deptName: '',
        recTypeId: '',
        recTypeCode: '',
        recTypeName: '',
        ruleId: '',
        orderStatus: 'N',
        moveMaterialType: 'receive',
        moveMaterialSource: 'orderCode',
        sourceNo: '',//todo 测试-上线前后续不默认数据
        remarks: '',
        applicant: '',
        moveMaterialTypeReturn: '',
        moveMaterialReturnAbove: '',

        receiveWc:'',//车间主档编码=WMS货位
        receiveWcName:'',
        issueWarehouse:'',//出库仓库编码
        issueWarehouseName:'',
        issueWarehouseU8:'',//U8对应的仓库编码
        pickType:'领料申请单',
        //2025-04-18流程卡信息
        // 2025-04-21修改为生产订单
        sourceNoInfo:[],
        htWmsStatus:0,
        targetLocationId:'',
        targetLocationCode:'',
        targetLocationName:'',
        targetLocationList:[],
        targetLocationKind:'MWC',//WINV -MWC
      },
      mpMtlSnHtWmsList: [],

      tableList: [],
      // dialog参数
      dialogFilters: {
        materialCode: '',
        materialDesc: '',
        locationKind: '',
        locationId: '',
        mtlgroupNo: '', // 批次号
        lotNo: '', // 生产订单号
        woCode: '', // 工单号
        materialBarcode: '', //物料条码号
        sourceNo: '', // 来源单号
      },
      dialogList: [],
      dialogTablePag: {
        pageNo: 1,
        pageSize: 10,
        totalRecord: 0,
      },
      dialogPeoplePag: {
        pageNo: 1,
        pageSize: 10,
        totalRecord: 0,
      },
      dialogIsShow: false,
      dialogPeopleIsShow: false,
      selectedDialogRow: [],
      selectedPeopleRow: {},
      dialogListHeader: [
        {
          name: '物料批次',
          code: 'mtlgroupNo',
          width: '200',
        },
        {
          name: '物料编码',
          code: 'materialCode',
          width: '160',
        },
        {
          name: '物料名称',
          code: 'materialName',
          width: '160',
        },
        {
          name: '物料型号',
          code: 'materialDesc',
          width: '160',
        },
        {
          name: '数量',
          code: 'mtlQty',
          width: '80',
        },
        {
          name: '当前位置类型',
          code: 'locationKindName',
          width: '120',
        },
        {
          name: '当前位置',
          code: 'locationName',
          width: '120',
        },
        {
          name: '生产日期',
          code: 'manufactureDateStr',
          width: '160',
        },
        {
          name: '剩余有效期',
          code: 'remainPeriodName',
          width: '120',
        },
      ],
      materialBarcodeHeader: [
        {
          name: '物料条码',
          code: 'materialBarcode',
          width: '200',
        },
        {
          name: '数量',
          code: 'materialQty',
          width: '100',
        },
        {
          name: '物料批次',
          code: 'mtlgroupNo',
          width: '250',
        },
        {
          name: '生产日期',
          code: 'manufactureDateStr',
          width: '250',
        },
        {
          name: '失效日期',
          code: 'dvDateStr',
          width: '250',
        },
      ],
      dialogPeople: {
        userCode: '',
        userName: '',
      },
      dialogPeopleHeader: [
        {
          name: '用户编码',
          code: 'userCode',
        },

        {
          name: '用户名称',
          code: 'userName',
        },
      ],
      dialogPeopleList: [], // 移料人弹框
      paramsMaterial: {},
      paramsPeople: {},
      // 移料人所在行的索引
      peopleIndex: '',
      clickType: '',
      selectionData: {},
      count: 0,
      dataList: [],
      // 当前选中的批次的index
      nowIndex: 0,
      // 已扫描的序列号集合
      mtlSnArr: [],
      mtlSnArrD: [],
      selectedSnRow: [],
      selectRowOld: [],
      // 验证规则
      rules: {
        deptId: [{ required: true, message: '请选择开立部门', trigger: 'change' }],
        recTypeName: [{ required: true, message: '请选择单据类型', trigger: 'change' }],
        activityTime: [{ required: true, message: '请选择移料日期', trigger: 'change' }],
        officeId: [{ required: true, message: '请选择车间', trigger: 'change' }],
        moveMaterialType: [{ required: true, message: '请选择移料类别', trigger: 'change' }],
        moveMaterialSource: [{ required: true, message: '请选择移料来源', trigger: 'change' }],
        sourceNo: [{ required: true, message: '请填写移料来源单号', trigger: 'change' }],
        applicant: [{ required: true, message: '请选择申请人', trigger: 'change' }],
        materialBarcode: [{ required: true, message: '请扫描或输入物料条码', trigger: 'change' }],
        moveMaterialTypeReturn: [{ required:false, message: '请选择退料类型', trigger: 'change' }],
        moveMaterialReturnAbove: [{ required: false, message: '请选择退料是超额', trigger: 'change' }],
      },
      deptSel: [],
      listHeight: 200,
      selectedRowSn: [],
      dialogTemShow: false,
      templateList: [],
      template: '',
      mtlBtnConfig: [
        {
          label: '删除',
          name: 'delete',
          type: 'danger',
          cb: (...args) => {
            this.deleteRow(args[1], this.tableList);
          },
        },
      ],
      mtlBtnConfigCode: [
        {
          label: '删除',
          name: 'delete',
          type: 'danger',
          cb: (...args) => {

            console.log(args,'mtlBtnConfigCode');
            this.deleteRowCode(args[1]);
          },
        },
      ],
      moveMaterialTypeList: [],
      moveMaterialSourceList: [],
      moveMaterialTypeReturnList:[],
      moveMaterialReturnAboveList:[{ label: '正常', value: 'N'},{ label: '超额', value: 'Y'}],
      currentId: '',
      dialogApplicantIsShow: false,
      topBtnConfig: [
        {
          name: 'confirm',
          label: '保存提交',
          type: 'primary',
          eleType: 'confirm',
          cb: this.confirm,
        },
        // {
        //   name: 'save',
        //   label: '保存',
        //   type: 'primary',
        //   cb: this.saveInfo,
        // },
        // {
        //   name: 'print',
        //   label: '标签打印',
        //   type: 'success',
        //   cb: this.dialogShow,
        // },
        {
          name: 'back',
          label: '返回',
          type: 'danger',
          cb: this.back,
        },
      ],

      receiveWcList:[

          //todo 货位没有用处-废弃状态
        {label:'前道线边仓',value:'002',prodorgCode:'D61'},
        {label:'后道线边仓',value:'003',prodorgCode:'D62'},
        {label:'测试线边仓',value:'005',prodorgCode:'D63'},
      ],
      issueWarehouseList:[
        // {label:'前道(车间仓库一区)',value:'B02',prodorgCode:'D61'},
        // {label:'后道(车间仓库二区)',value:'B03',prodorgCode:'D62'},
        // {label:'包装(车间仓库三区)',value:'B04',type:'包装'},
        // {label:'测试(车间仓库四区)',value:'B05',prodorgCode:'D63'},
      ],
      bomList:[],//批次的BOM
      orderBomOrgList:[],
      isDisableStatus:false,
      mtlStockQty:0,//条码库存
      isMesTest:false,//系统测试-关闭一些卡控
      locationTypeArrHtWms:[],//目标工作中心
      htWmsWarehouseList:[],//WMS仓库底表
      orderReveivedList:[]//订单累计已领取数量
    };
  },
  methods: {
    async handleConfirmTem(form) {
      let loadRes = await this.LoadScript(`http://${form.ip}:8000/CLodopfuncs.js?priority=1`).catch(err => {
        this.$message.warning(err);
      });
      if (!loadRes) {
        return;
      }
      const param = { printTemplateId: form.templateId, id: this.currentId };
      getPrintInfo(param).then(res => {
        if (res.success) {
          res.rows.forEach(item => {
            print({ components: item.components, templateInfo: item.templateInfo, printName: form.name });
          });
          this.dialogTemShow = false;
          this.$message.success('已开始打印');
        }
      });
    },
    LoadScript(url) {
      return new Promise((resolve, reject) => {
        if (!url) {
          return reject('url不存在');
        }
        let lodopEl = document.getElementById('lodop');
        if (lodopEl) {
          let ourl = lodopEl.src;
          let ourIndex = ourl.indexOf('&v');
          ourl = ourl.substring(0, ourIndex);

          if (ourl === url) {
            resolve({});
            return;
          }
          lodopEl.remove();
        }
        const script = document.createElement('script');
        script.src = url + '&v=' + new Date().getTime();
        script.id = 'lodop';
        script.type = 'text/javascript';
        script.onerror = () => {
          reject(`${url}加载不成功`);
          console.log(`${url}加载不成功`);
        };
        script.onload = () => {
          console.log('load lodop');
          if (window.LODOP) {
            console.log('load lodop1 ');
            window.LODOP.SET_LICENSES('', window.LODOP_LICENSE, '', '');
          }
          resolve({});
        };
        document.getElementsByTagName('head')[0].appendChild(script);
      });
    },
    confirmTem() {
      let type = '';
      if (this.selectionData.serializedFlag === 'Y') {
        type = 'SN';
      } else {
        type = 'MTL';
      }
      let list = [];
      let snList = this.selectionData.mpInvActivitySnHtWmsList || [];
      snList.forEach(item => {
        list.push({
          id: item.id,
          materialQty: item.materialQty,
        });
      });
      let params = {
        id: this.template,
        type: type,
        mpInvActivityDtlEntity: {
          id: this.selectionData.originalId,
          mtlQty: this.selectionData.mtlQty,
          mpInvActivitySnHtWmsList: list,
        },
      };
      let str = JSON.stringify(params).replace(/"/g, "'");
      console.log(str);
      let printUrl = "codesoftprint://params={'page':'MTL','param':" + str + '}/';
      console.log(printUrl);
      window.location.href = printUrl;
      this.dialogTemShow = false;
    },
    closeTem() {
      this.dialogTemShow = false;
    },

    print() {
      if (!this.selectionData.originalId) {
        this.$message({
          duration: 1500,
          type: 'warning',
          message: '请选择物料信息',
        });
        return;
      }
      this.dialogTemShow = true;
      this.template = '';
    },
    //ezio  序列号列表
     getSnNew() {
      return  false;
    },
    async getSn() {

      let data = this.selectionData;
      // console.log(this.selectionData)
      let list = _.cloneDeep(this.selectionData.mpInvActivitySnHtWmsList);
      // console.log(list)
      let param = {
        locationId: data.originalLocationId,
        mtlKind: data.mtlKind,
        mtlgroupNo: data.batchNo,
      };
      let res = await getSn(param);
      if (res.success) {
        let snArr = (res.mpInvMtlLocSnList || []).map(item => {
          let obj = {
            materialBarcode: item.materialBarcode,
            materialQty: item.mtlQty,
            // selFlag: '0',
            activeFlag: item.activeFlag,
            materialState: item.materialState,
            verNo: item.verNo,
            serialmtlId: item.id,
          };
          return obj;
        });

        this.mpMtlSnHtWmsList = _.cloneDeep(snArr);
        this.selectedSnRow = _.cloneDeep(snArr);
        for (let item of this.mpMtlSnHtWmsList) {
          let flag = list.some(childItem => childItem.materialBarcode === item.materialBarcode);
          if (flag) {
            this.$nextTick(() => {
              this.$refs.mtlSnTable.toggleRowSelection(item, true);
            });
          }
        }
      }
    },
    /**
     * 选择当前行事件
     */
    currentRowChange(val) {

      //todo 暂时关闭
      // return false;

      this.mpMtlSnHtWmsList = [];
      this.basicInfo.materialBarcode = '';
      this.selectionData = val || {};
      this.basicInfo.batchNo = this.selectionData.batchNo || '';
      this.basicInfo.mtlKind = this.selectionData.mtlKind || '';
      this.basicInfo.locationId = this.selectionData.originalLocationId || '';
      this.basicInfo.locationKind = this.selectionData.locationKind || '';
      this.selectedRowSn = [];
      this.nowIndex = val.index;
      this.currentId = val.originalId;

      //todo ezio 物料下模板未试用，暂废弃
      // if (this.selectionData.materialId !== '') {
      //   let params = {
      //     materialId: this.selectionData.materialId,
      //   };
      //   getTemList(params).then(res => {
      //     if (res.success) {
      //       this.templateList = res.mcPkgLabelTemplateList || [];
      //     }
      //   });
      // }


      this.mpMtlSnHtWmsList = _.cloneDeep(val.mpInvActivitySnHtWmsList);
      return;


      // //todo 用不着 已有序列号
      // if (val.mpInvActivitySnHtWmsList.length >= 1) {
      //   if (!val.targetLocationId) {
      //     return;
      //   }
      //   this.selectionData.mpInvActivitySnHtWmsList = _.cloneDeep(val.mpInvActivitySnHtWmsList);
      //   this.getSnNew();
      //
      // }
    },
    /**
     * 根据物料条码查询物料信息
     */
    enterSnNew() {

      if (this.bomList.length<1) {
        this.$message({
          duration: 1500,
          type: 'warning',
          message: '提示：请先输入移动来源单号，注意按回车。',
        });
        return;
      }
      if (!this.basicInfo.materialBarcode) {
        return;
      }

      //物料条码有唯一性,不可重复扫描
      if(this.mtlSnArr.indexOf(this.basicInfo.materialBarcode)>-1){
        this.$message.warning('物料条码已扫描过');
        return false;
      }
      //BOM对应的仓库物料信息
      // if(this.basicInfo.issueWarehouse==undefined ||this.basicInfo.issueWarehouse=="" ){
      //   this.getDataByByProdorgCode(this.prodorgCode);
      // }



      let params = {
        cbarcode: this.basicInfo.materialBarcode,
      };
        htWmsGetDataByBarcode(params).then(res => {

        console.log(res,'htWmsGetDataByBarcode-res');

        //1）物料条码唯一性
        if (res.status==200) {
          if(res.data===undefined){
            this.$message({
              duration: 3000,
              type: 'warning',
              message: '提示：没有查询到相应物料，请查看物料条码是否正确',
            });
            return;
          }

          let wmsMtlinfo = res.data[0];
          //todo 2) 物料是否在库
          if(wmsMtlinfo.CSTATE!='在库')
          {
            this.$message.warning('物料条码对应的物料'+wmsMtlinfo.INVCODE+"不在库，状态是"+wmsMtlinfo.CSTATE);
            return false;
          }
          //如果不在线边库
          // let issue_index = this.issueWarehouseList.findIndex(item=>item.value==wmsMtlinfo.WHCODE);


          if(this.basicInfo.issueWarehouse!=wmsMtlinfo.WHCODE){

            if(this.tableList.length>0){
              this.$message.warning('线边仓需要申请一致，物料条码不在线边仓'+this.basicInfo.issueWarehouse+'，在'+wmsMtlinfo.WHCODE);
              return false;
            }

            //判断如果是同个车间，修改issueWarehouse
            let issue_info = this.issueWarehouseList.find(items_lt=>items_lt.value==wmsMtlinfo.WHCODE);
            if(issue_info!==undefined&&issue_info.prodorgCode==this.prodorgCode){
              this.basicInfo.issueWarehouse = issue_info.value;
              this.basicInfo.issueWarehouseName = issue_info.label;
              this.basicInfo.issueWarehouseU8 = issue_info.u8HouseCode;
            }
            else{
              this.$message.warning('物料条码不在线边仓'+this.basicInfo.issueWarehouse+'，在'+wmsMtlinfo.WHCODE);
              return false;
            }
          }

          //todo 为了测试方便关闭  3) 卡控是否在订单的BOM的物料
          let bomItem = this.bomList.find(items_lt=>items_lt.materialCode==wmsMtlinfo.INVCODE);
          if(bomItem===undefined){
            console.log(  '提示：添加失败，条码'+this.basicInfo.materialBarcode+'的物料'+wmsMtlinfo.INVCODE+"不是该生产订单的BOM物料！",'bomInfo');

            // this.$message({
            //   duration: 3500,
            //   type: 'warning',
            //   message: '提示：添加失败，条码'+this.basicInfo.materialBarcode+'的物料'+wmsMtlinfo.INVCODE+"不是该生产订单的BOM物料,当前暂不卡控",
            // });
            if(!this.isMesTest){
              this.$message({
                duration: 1500,
                type: 'warning',
                message: '提示：添加失败，条码'+this.basicInfo.materialBarcode+'的物料'+wmsMtlinfo.INVCODE+"不是该生产订单的BOM物料！",
              });
              return;
            }
            else{
              //模拟bom信息
              bomItem = {
                unit:'EA',
                usage:2,
                changeRate:7,
              }
            }
            console.log(bomItem,'bom信息');
          }
          let mtlUomname = bomItem.unit;
          let usageItem = bomItem.usage;
          let dieQtyItem = this.basicInfo.sourceNoInfo.dieQty;
          let orderBomQtyItem = this.changeNumberHt(usageItem* dieQtyItem);
          //todo 同个物料-换算率有可能不同-历史原因-暂不考虑
          let changeRateNewItem = this.changeNumberHt(bomItem.changeRate);
          let orderMaterialUsedQty = this.changeNumberHt(bomItem.orderMaterialUsedQty);
          let orderMaterialNeedQty = this.changeNumberHt(bomItem.orderMaterialNeedQty);
          let planQty = this.changeNumberHt(bomItem.planQty);

          //todo 超耗领料完成前不启用剩余数量判断orderMaterialNeedQty-物料批次的线边仓-库存
          let  oldQty = 0;

          //4）查询WMS库存数量，如果已查询，可以不查询，后台判断是否库存存在
          //异步方法
          // if(!this.isMesTest){
          //   findHtWmsLineStock({
          //     INVCODE: wmsMtlinfo.INVCODE,
          //     WHCODE: this.basicInfo.issueWarehouse,
          //     // BATCH:wmsMtlinfo.INVCODEHB, //有没有带有物料编码
          //     //条码唯一性能否保证
          //     BARCODENO: this.basicInfo.materialBarcode,//条码唯一性
          //   }).then(res => {
          //     if (res.status == 200) {
          //       if (res.data != undefined) {
          //         oldQty = res.data[0].TOTALQTY;
          //       }
          //     }
          //
          //     this.mtlStockQty = oldQty;
          //     this.tableList[this.nowIndex].mtlQty = oldQty;
          //     console.log(res,BARCODENO+'条码的库存-htWmsLineStock-res');
          //     console.log(oldQty,INVCODE+'最新库存-oldQty-new');
          //     if(oldQty<=0){
          //       this.$message({
          //         duration: 3500,
          //         type: 'warning',
          //         message: '提示：'+wmsMtlinfo.BARCODENO+"查询不到库存。",
          //       });
          //       return;
          //     }
          //     //todo  下面实体代码需要引入这里
          //
          //   });
          // }
          // else{
          //   oldQty = '999999999';
          // }



          //原位置选择
          let location_info = this.locationTypeArr.find(items_lt=>items_lt.value=='WINV');
          let target_info = this.locationTypeArr.find(items_lt=>items_lt.value=='MWC');

          //物料条码列表
          let barcodeObj =  {
            mtlgroupNo:wmsMtlinfo.INVCODEHB,
            materialCode:wmsMtlinfo.INVCODE,
            materialDesc:wmsMtlinfo.INVSTD,
            materialName:wmsMtlinfo.INVNAME,
            // qty:wmsMtlinfo.QTY,
            materialBarcode:wmsMtlinfo.BARCODENO,
            materialQty:wmsMtlinfo.QTY,
            activeFlag: 'Y',
            verNo:'99',
            materialState:'Normal',
            serialmtlId:0,
            indexNo:0,
            manufactureDate:(wmsMtlinfo.MAKEDATE).toString().substr(0,10),
            manufactureDateStr:(wmsMtlinfo.MAKEDATE).toString().substr(0,10),
            dvDate:(wmsMtlinfo.DVDATE).toString().substr(0,10),
            dvDateStr:(wmsMtlinfo.DVDATE).toString().substr(0,10),
            mtlBatch:wmsMtlinfo.BATCH,
          }
          //物料列表新增
          //物料批次在物料列表是否已存在
          let index = this.tableList.findIndex(items_lt=>items_lt.materialCode==wmsMtlinfo.INVCODE);
          let tableInfo = this.tableList.find(items_lt=>items_lt.materialCode==wmsMtlinfo.INVCODE);
          let mtlQty = this.changeNumberHt(wmsMtlinfo.QTY);


          //todo 如果物料换算率有效，标签扫码总数不应该大于流程卡需要的总数


          //物料条码有唯一性,不可重复扫描
          if(this.mtlSnArr.indexOf(this.basicInfo.materialBarcode)>-1){
            this.$message.warning('物料条码已扫描过，二级卡控！');
            return false;
          }

          //判断该物料批次是否已存在
          if(index>-1){
            //物料条码列表
            this.mpMtlSnHtWmsList = _.cloneDeep(tableInfo.mpInvActivitySnHtWmsList);
            let indexNo =   this.mpMtlSnHtWmsList.length;
            barcodeObj.indexNo = indexNo;
            this.mpMtlSnHtWmsList.push(barcodeObj);
            //可领-移料数量
            orderMaterialNeedQty = this.changeNumberHt(orderMaterialNeedQty-mtlQty);
            //更新物料对应的数量
            mtlQty = mtlQty+tableInfo.mtlQty;
            //库存卡控不开启，条码有库存状态了。
            oldQty = mtlQty;

            this.$set(this.tableList,index,{
              ...tableInfo,
              oldQty: oldQty, // 条码-库存数量
              mtlQty: mtlQty, // 移料数量小于等于条码数量
              mtlSpuqty:indexNo+1,//序列数量=物料条码数量
              mpInvActivitySnHtWmsList:this.mpMtlSnHtWmsList,
              orderMaterialNeedQty:orderMaterialNeedQty
            });


          }
          else{
            this.mpMtlSnHtWmsList = [];
            this.mpMtlSnHtWmsList.push(barcodeObj);

            //库存卡控不开启，条码有库存状态了。
            oldQty = mtlQty;
            // console.log(this.basicInfo,'this.basicInfo');
            //初始化-新增物料
            this.tableList.push({
              ...wmsMtlinfo,
              index: this.tableList.length,
              count: 0,
              mtlgroupId: '',//todo ezio空值
              locationKind: location_info.value,
              originalLocationKind: location_info.value, // 元未知类型
              originalLocationKindName:location_info.label,
              originalLocationId:  location_info.id, //原位置id 非空,
              originalLocationCode: 'D999999', //WMS线边仓 原位置编码 非空,
              originalLocationName: this.basicInfo.issueWarehouseName, // 原位置名称 非空,
              targetLocationKind: target_info.value, // 目标位置类型 非空,
              targetLocationId: "", // 目标位置id 非空,
              targetLocationCode: "", // 目标位置编码 非空,
              targetLocationName:"", // 目标位置名称 非空,
              batchNo: wmsMtlinfo.INVCODEHB, // 物料批次号 非空,== 无意义了
              materialId: 0, // 物料ID 非空,
              materialCode: wmsMtlinfo.INVCODE, // 物料编码,
              materialName: wmsMtlinfo.INVNAME, // 物料名称,
              materialDesc: wmsMtlinfo.INVSTD, // 规格型号,
              oldQty: oldQty, // 原库存数量 非空,
              mtlQty:mtlQty, // 数量 非空, 移料数量--换算率后的结果orderMaterialQtyItem，但是由于条码存在，直接使用数量
              mtlUom: "", // todo 计量单位ID 非空,
              mtlUomname: mtlUomname, // 计量单位名,
              relateduserId: this.basicInfo.relateduserId ? this.basicInfo.relateduserId : '', // 移料人id 非空,
              relateduserCode: this.basicInfo.relateduserCode ? this.basicInfo.relateduserCode : '', // 移料人编码,
              relateduserName: this.basicInfo.relateduserName ? this.basicInfo.relateduserName : '', // 移料人名称,
              lotcontrolledFlag: 'N', // 批次管理， 物料选择中批次管理字段， Y - 是， N - 否 非空,
              mtlSpy: "", // SN单位,===============新增===============
              mtlSpyname: "", // SN单位名称,===============新增===============
              mtlSpuqty:1, // 序列数量,===============新增===============
              mtlKind: "", // 物料类别,===============新增===============
              mtlKindName: "",
              serializedFlag: "N", // 序列管理，Y-是，N-否===============新增===============
              targetLocationList: [],
              mpInvActivitySnHtWmsList: this.mpMtlSnHtWmsList,
              onlyId: "",
              claimEqpCode: "",//设备编码
              claimEqpName: "",
              claimEqpId: "",
              //ezio 新增字段
              mtlBomQty:orderBomQtyItem,//BOM应该用多少物料
              usage:usageItem,
              changeRateNew:changeRateNewItem,
              lotDieQty:dieQtyItem,
              mtlBatch: wmsMtlinfo.BATCH, // 物料批号,
              orderMaterialUsedQty:orderMaterialUsedQty,//已领数量
              orderMaterialNeedQty:orderMaterialNeedQty,//剩余可领数量
              planQty:planQty,
            })
          }
          console.log(this.mpMtlSnHtWmsList,'mpMtlSnHtWmsList');

          this.mtlSnArr.push(this.basicInfo.materialBarcode);
          let table_len = this.tableList.length-1;
          //目标位置选择
          this.onSelectTarget(this.tableList[table_len],table_len);

          this.$refs.mtlSnTable.toggleRowSelection(barcodeObj, true);
          this.selectedRowSn.push(barcodeObj);

          this.basicInfo.materialBarcode = '';
          this.isDisableStatus = true;

        }
        else{
          this.$message({
            duration: 1500,
            type: 'warning',
            message: '提示：'+res.massage,
          });
          return;
        }
      });
    },
    /**
     * 根据序列号+物料批次号查询序列信息
     */
    enterSn() {
      if (!this.basicInfo.materialBarcode) {
        return;
      }
      // // 验证重复
      // let isExisted = false
      // if (this.mpMtlSnHtWmsList) {
      //   this.mpMtlSnHtWmsList.forEach(item => {
      //     if (item.materialBarcode === this.basicInfo.materialBarcode) {
      //       isExisted = true
      //       return false
      //     }
      //   })
      // }
      // if (isExisted) {
      //   this.$message.warning({
      //     message: '序列号不得重复扫描'
      //   })
      //   return
      // }
      // 验证可用
      let count = 0;
      let msg = '';
      let snObj = '';
      this.basicInfo.materialBarcode = this.basicInfo.materialBarcode.replace(/(^\s*)|(\s*$)/g, '');
      let kind = this.tableList[this.nowIndex].targetLocationKind === 'MWC';
      this.mpMtlSnHtWmsList.forEach(item => {
        // 有此序列号
        if (item.materialBarcode === this.basicInfo.materialBarcode) {
          // 目标为工作中心
          if (kind) {
            // 符合条件
            if (item.activeFlag === 'Y' && item.materialState === 'Normal') {
              snObj = item;
            } else {
              msg = '此序列号不可用';
            }
          } else {
            snObj = item;
          }
          count++;
          return false;
        }
      });
      if (count <= 0) {
        this.$message.warning({
          message: '此序列号不存在',
          duration: 1500,
        });
        this.basicInfo.materialBarcode = '';
        return;
      } else if (msg) {
        this.$message.warning({
          message: msg,
          duration: 1500,
        });
        this.basicInfo.materialBarcode = '';
        return;
      }
      this.$refs.mtlSnTable.toggleRowSelection(snObj, true);
      this.basicInfo.materialBarcode = '';
      this.selectedRowSn.push(snObj);
    },
    /**
     * @name:deleteRow
     * @description:默认标准删除行
     * @param {type}:
     */
    deleteTmp(index, rows) {
      const mtlListClone = _.cloneDeep(this.mpMtlSnHtWmsList);
      this.$confirm('确认删除选中的数据？')
        .then(_ => {
          // console.log(rows)
          this.tableList[this.nowIndex].count = this.selectionData.mtlQty;
          this.mpMtlSnHtWmsList.splice(index, 1);
          //数据删除就清空
          this.selectionData.mtlQty = parseFloat(this.selectionData.mtlQty) - parseFloat(rows.materialQty);
          this.tableList[this.nowIndex].count = this.selectionData.mtlQty;
          this.selectionData.mtlSpuqty = parseFloat(this.selectionData.mtlSpuqty) - 1;
          this.selectionData.mpInvActivitySnHtWmsList = this.mpMtlSnHtWmsList;
          // 赋值
          /// this.tableList[this.nowIndex].mtlQty = parseFloat(this.selectionData.mtlQty) - parseFloat(rows.materialQty)
          this.tableList[this.nowIndex].mtlQty = parseFloat(this.selectionData.mtlQty);

          // this.tableList[this.nowIndex].mtlSpuqty = parseFloat(this.selectionData.mtlSpuqty) - 1
          this.tableList[this.nowIndex].mtlSpuqty = parseFloat(this.selectionData.mtlSpuqty);

          this.tableList[this.nowIndex].mpInvActivitySnHtWmsList = this.mpMtlSnHtWmsList;

          // 已使用序列号赋值
          // console.log(this.mtlSnArr.indexOf(mtlListClone[index].materialBarcode))
          let snIndex = this.mtlSnArr.indexOf(mtlListClone[index].materialBarcode);
          // console.log(this.mtlSnArr)
          this.mtlSnArr.splice(snIndex, 1);
          // console.log(this.mtlSnArr)
          // console.log(this.mpMtlSnHtWmsList)

          //清空释放数据
          this.reSetData();
        })
        .catch(_ => {});
    },
    /**
     * @name:back
     * @description:返回
     * @param {type}:
     */
    back() {
      this.$router.push({
        name: 'moveIndexHtModule',
      });
    },
    // 申请人弹框
    showApplicantDialog() {
      this.dialogApplicantIsShow = true;
    },
    closeApplicationDialog(flag) {
      this.dialogApplicantIsShow = flag;
    },
    setApplicantPerson(row) {
      this.basicInfo.applicant = row.userName;
      this.basicInfo.applicantId = row.userId;
    },
    /**
     * 加载车间下拉框
     */
    // getFactory () {
    //   let param = {
    //     'requestId': uuid(32, 32)
    //   }
    //   initPage(param)
    //     .then(res => {
    //       if (res.success === true) {
    //         this.factoryArr = res.companyList // 车间列表

    //         this.locationTypeArr = res.locationKindList // 目标位置类型
    //       }
    //     })
    //     .catch(() => { })
    // },

    onSelectTarget(row, index) {
      let param = {
        requestId: uuid(32, 32),
        locationKind: row.targetLocationKind,
        updateFlag: 'true',
        prodorgId: this.basicInfo.officeId, // 车间id 非空
      };
      getBySelection(param)
        .then(res => {
          if (res.success === true) {
            row.targetLocationId = '';
            row.targetLocationList = [];
            // row.targetLocationList = []
            if (row.targetLocationKind === 'WINV') {
              for (let item of res.allLocList) {
                let obj = {
                  id: item.id,
                  code: item.locationCode,
                  name: item.locationName,
                };
                row.targetLocationList.push(obj);
              }
              // console.log(row.targetLocationList)
            } else {
              for (let item of res.workcenterList) {
                let obj = {
                  id: item.id,
                  code: item.workcenterCode,
                  name: item.workcenterName,
                };
                row.targetLocationList.push(obj);
              }
              // console.log(row.targetLocationList)
            }

            //ezio 默认选中目标位置
            row.targetLocationKind = this.basicInfo.targetLocationKind;
            row.targetLocationId = this.basicInfo.targetLocationId;
            row.targetLocationCode = this.basicInfo.targetLocationCode;
            row.targetLocationName = this.basicInfo.targetLocationName;

            this.$set(this.tableList, index, row);

            if (this.selectionData.index === row.index) {

              //todo ezio 不理解为何要求清空
              // this.mpMtlSnHtWmsList = [];
            }
          } else {
            // this.$message({
            //   message: res.msg,
            //   type: 'danger'
            // })
          }



        })
        .catch(() => {});
    },

    onSelectTargetBasic() {
      if (this.basicInfo.officeId === '' || this.basicInfo.officeId === null) {
        this.$message({
          duration: 1500,
          message: '请选择车间',
          type: 'warning',
        });
        return false;
      }

      let param = {
        requestId: uuid(32, 32),
        locationKind: this.basicInfo.targetLocationKind,
        updateFlag: 'true',
        prodorgId: this.basicInfo.officeId, // 车间id 非空
      };
      getBySelection(param)
          .then(res => {
            if (res.success === true) {
              this.basicInfo.targetLocationId = '';
              this.basicInfo.targetLocationList = [];
              // row.targetLocationList = []
              if (this.basicInfo.targetLocationKind === 'WINV') {
                for (let item of res.allLocList) {
                  let obj = {
                    id: item.id,
                    code: item.locationCode,
                    name: item.locationName,
                  };
                  this.basicInfo.targetLocationList.push(obj);
                }
                // console.log(row.targetLocationList)
              } else {
                for (let item of res.workcenterList) {
                  let obj = {
                    id: item.id,
                    code: item.workcenterCode,
                    name: item.workcenterName,
                  };
                  this.basicInfo.targetLocationList.push(obj);
                }
                // console.log(row.targetLocationList)
              }

            } else {
              // this.$message({
              //   message: res.msg,
              //   type: 'danger'
              // })
            }
          })
          .catch(() => {});
    },
    getCode(val, index) {
      // console.log(val.targetLocationList)
      for (let item of val.targetLocationList) {
        // if (val.targetLocationKind === 'WINV') {
        if (val.targetLocationId === item.id) {
          val.targetLocationId = item.id;
          val.targetLocationCode = item.code;
          val.targetLocationName = item.name;
        }
        // this.locationCode = item.locationCode
        // this.locationName = item.locationName
        // } else {
        //   this.locationCode = item.workcenterCode
        //   this.locationName = item.workcenterName
        // }
      }
      // this.tableList[index].mpInvActivitySnHtWmsList.forEach(item => {
      //   item.selFlag = '0'
      // })
      // this.mpMtlSnHtWmsList = this.tableList[index].mpInvActivitySnHtWmsList
      if (val.serializedFlag !== 'Y') {
        return;
      }
      this.mpMtlSnHtWmsList = this.selectedSnRow;
      let list = this.selectionData.mpInvActivitySnHtWmsList || [];
      for (let item of this.mpMtlSnHtWmsList) {
        let flag = list.some(childItem => childItem.materialBarcode === item.materialBarcode);
        if (flag) {
          this.$nextTick(() => {
            this.$refs.mtlSnTable.toggleRowSelection(item, true);
          });
        }
      }

      // console.log(val)
    },


    getCodeBasic() {
      // console.log(val.targetLocationList)
      for (let item of this.basicInfo.targetLocationList) {
        // if (val.targetLocationKind === 'WINV') {
        if (this.basicInfo.targetLocationId === item.id) {
          this.basicInfo.targetLocationId = item.id;
          this.basicInfo.targetLocationCode = item.code;
          this.basicInfo.targetLocationName = item.name;
        }
      }

      //物料列表，默认选中目标位置
      if(this.tableList.length>0){
        this.tableList.some(item => {
           item.targetLocationId = this.basicInfo.targetLocationId;
           item.targetLocationCode = this.basicInfo.targetLocationCode;
           item.targetLocationName = this.basicInfo.targetLocationName;
        });
      }
    },

    /**
     * 加载物料弹框form表单位置类型下拉框
     */
    getDialogSelection() {
      let param = {
        requestId: uuid(32, 32),
      };
      initPage(param)
        .then(res => {
          if (res.success === true) {
            this.formLocationTypeArr = res.locationKindList; // 位置类型
          } else {
            // this.$message({
            //   message: res.msg,
            //   type: 'danger'
            // })
          }
        })
        .catch(() => {});
    },
    onSelectFormType(val) {
      this.dialogFilters.locationId = '';
      if (this.dialogFilters.locationKind === '' || this.dialogFilters.locationKind === null) {
        return false;
      }
      let param = {
        requestId: uuid(32, 32),
        locationKind: val,
        updateFlag: 'false',
      };
      getBySelection(param)
        .then(res => {
          if (res.success === true) {
            this.formLocationArr = [];
            if (val === 'WINV') {
              for (let item of res.allLocList) {
                let obj = {
                  id: item.id,
                  code: item.locationCode,
                  name: item.locationName,
                };
                this.formLocationArr.push(obj);
              }
            } else {
              for (let item of res.workcenterList) {
                let obj = {
                  id: item.id,
                  code: item.workcenterCode,
                  name: item.workcenterName,
                };
                this.formLocationArr.push(obj);
              }
            }
          } else {
            // this.$message({
            //   message: res.msg,
            //   type: 'danger'
            // })
          }
        })
        .catch(() => {});
    },
    /**
     * 拿到车间下拉框选择的值
     */
    getSelection(val) {
      this.basicInfo.relateduserName = '';
      this.tableList = [];
      this.basicInfo.officeId = val;

      for (let item of this.factoryArr) {
        if (this.basicInfo.officeId === item.id) {
          this.prodorgCode = item.officeCode;
          this.prodorgName = item.officeName;

          //BOM对应的仓库物料信息
          this.getDataByByProdorgCode(this.prodorgCode);
        }
      }
      this.selectDefaultRelateduserName();

      //限制显示目标位置
      this.locationTypeArrHtWms = this.locationTypeArr.filter(item => item.value==this.basicInfo.targetLocationKind);
      this.onSelectTargetBasic();

    },
    /**
     * 车间移料时，移料人默认选中当前用户，不在车间的不自动选
     */
    selectDefaultRelateduserName() {
      findPeople({
        prodorgId: this.basicInfo.officeId,
        pageSize: 10,
        pageNo: 1,
        userCode: this.account.userNo,
      }).then(res => {
        let user = {};
        if (res.success && res?.rows?.length === 1) {
          user = res.rows[0];
        }
        this.basicInfo.relateduserName = user.userName || '';
        this.basicInfo.relateduserId = user.userId || '';
        this.basicInfo.relateduserCode = user.userCode || '';
      });
    },
    // 打开物料批次弹窗
    showDialog() {
      this.selectedDialogRow = [];
      this.dialogFilters.materialCode = '';
      this.dialogFilters.materialDesc = '';
      this.dialogFilters.locationKind = '';
      this.dialogFilters.locationId = '';
      this.dialogFilters.mtlgroupNo = ''; // 批次号
      this.dialogFilters.lotNo = ''; // 生产订单号
      this.dialogFilters.woCode = ''; // 工单号
      // console.log(this.basicInfo.officeId)
      if (this.basicInfo.officeId === '' || this.basicInfo.officeId === null) {
        this.$message({
          duration: 1500,
          message: '请选择车间',
          type: 'warning',
        });
        return false;
      }
      this.dialogIsShow = true;

      this.getDialogSelection();
      this.paramsMaterial = {
        requestId: uuid(32, 32),
        pageSize: this.dialogTablePag.pageSize,
        pageNo: this.dialogTablePag.pageNo,
        prodorgId: this.basicInfo.officeId, // 车间id 非空
        mtlgroupNo: null, // 批次号
        materialCode: null, // 物料编码
        materialDesc: null, // 规格型号
        locationKind: null, // 位置类型
        locationId: null, // 位置
        queryFlag: this.basicInfo.moveMaterialReturnAbove=='Y'?'Y':'N', // 0也要显示
      };
      this.findMaterialList();

      console.log(this.tableList,'showDialog-this.tableList');
    },

    /**
     * 物料批次弹框的查询方法
     */
    findMaterialList() {
      findMaterialList(this.paramsMaterial)
        .then(res => {
          if (res.success === true) {
            // this.dialogList = res.rows
            this.dialogList = (res.rows || []).map((item, index) => {
              item.index = index + 1 + (this.dialogTablePag.pageNo - 1) * this.dialogTablePag.pageSize;
              return {
                ...item,
                remainPeriodName: item.remainPeriod ? `${item.remainPeriod}${item.remainPeriodUnitName}` : '',
              };
            });

            this.dialogTablePag.totalRecord = res.count || 0;
            this.$nextTick(_ => {
              this.$refs.singleTable.doLayout();
            });
            // this.dialogTablePag.totalRecord = res.count
          } else {
            // this.$message({
            //   message: res.msg,
            //   type: 'danger'
            // })
          }
        })
        .catch(() => {});
    },
    // 弹窗查询按钮
    searchDialogList() {
      this.selectedDialogRow = [];
      this.dialogTablePag.pageNo = 1;
      console.log(this.dialogFilters);
      this.paramsMaterial = {
        requestId: uuid(32, 32),
        pageSize: this.dialogTablePag.pageSize,
        pageNo: this.dialogTablePag.pageNo,
        prodorgId: this.basicInfo.officeId, // 车间id 非空
        materialCode: this.dialogFilters.materialCode, // 物料编码
        materialDesc: this.dialogFilters.materialDesc, // 规格型号
        locationKind: this.dialogFilters.locationKind, // 位置类型
        locationId: this.dialogFilters.locationId, // 位置
        mtlgroupNo: this.dialogFilters.mtlgroupNo, // 批次号
        lotNo: this.dialogFilters.lotNo, // 生产订单号
        woCode: this.dialogFilters.woCode, // 工单号
      };
      this.findMaterialList();
    },
    // 弹窗分页
    getDialogList(val) {
      this.dialogTablePag.pageNo = val;
      this.paramsMaterial.pageNo = val;
      this.findMaterialList();
    },
    // 弹窗多选
    selDialogRow(val) {
      this.selectedDialogRow = val;
    },
    selData(row) {
      let isExisted = this.tableList.some(item => {
        return item.batchNo === row.mtlgroupNo;
      });
      if (isExisted) {
        return;
      }
      this.selectedDialogRow = [row];
      this.saveDialogVal();
    },
    // 弹窗双击
    dbClickLot(val) {
      this.selectedDialogRow = [];
      this.selectedDialogRow.push(val);
      for (let item of this.selectedDialogRow) {
        let obj = {
          index: this.tableList.length,
          count: 0,
          mtlgroupId: item.mtlgroupId,
          locationKind: item.locationKind,
          originalLocationKind: item.locationKind, // 元未知类型
          originalLocationKindName: item.locationKindName,
          originalLocationId: item.locationId, // 原位置id 非空,
          originalLocationCode: item.locationCode, // 原位置编码 非空,
          originalLocationName: item.locationName, // 原位置名称 非空,
          targetLocationKind: '', // 目标位置类型 非空,
          targetLocationId: '', // 目标位置id 非空,
          targetLocationCode: '', // 目标位置编码 非空,
          targetLocationName: '', // 目标位置名称 非空,
          batchNo: item.mtlgroupNo, // 物料批次号 非空,
          materialId: item.materialId, // 物料ID 非空,
          materialCode: item.materialCode, // 物料编码,
          materialName: item.materialName, // 物料名称,
          materialDesc: item.materialDesc, // 规格型号,
          oldQty: item.mtlQty, // 原库存数量 非空,
          mtlQty: '', // 数量 非空,
          mtlUom: item.mtlUom, // 计量单位ID 非空,
          mtlUomname: item.mtlUomname, // 计量单位名,
          relateduserId: this.basicInfo.relateduserId ? this.basicInfo.relateduserId : '', // 移料人id 非空,
          relateduserCode: this.basicInfo.relateduserCode ? this.basicInfo.relateduserCode : '', // 移料人编码,
          relateduserName: this.basicInfo.relateduserName ? this.basicInfo.relateduserName : '', // 移料人名称,
          lotcontrolledFlag: item.lotcontrolledFlag, // 批次管理， 物料选择中批次管理字段， Y - 是， N - 否 非空,
          mtlSpy: item.mtlSpy, // SN单位,===============新增===============
          mtlSpyname: item.mtlSpyname, // SN单位名称,===============新增===============
          mtlSpuqty: '', // 序列数量,===============新增===============
          mtlKind: item.mtlKind, // 物料类别,===============新增===============
          mtlKindName: item.mtlKindName,
          serializedFlag: item.serializedFlag, // 序列管理，Y-是，N-否===============新增===============
          targetLocationList: [],
          mpInvActivitySnHtWmsList: [],
          onlyId: item.id,
          claimEqpCode: item.claimEqpCode,
          claimEqpName: item.claimEqpName,
          claimEqpId: item.claimEqpId,
        };
        this.tableList.push(obj);
      }
      // 只有一条时，默认选中
      if (this.tableList.length === 1) {
        // console.log('只有一条时，默认选中')
        this.$refs.tableList.setCurrentRow(this.tableList[0]);
      }
      this.$nextTick(() => {
        this.$refs.tableList.doLayout();
      });
      this.dialogIsShow = false;
    },
    // 保存
    saveDialogVal() {
      if (this.selectedDialogRow.length === 0) {
        this.$message({
          duration: 1500,
          message: '请至少选择一条数据',
          type: 'warning',
        });
        return false;
      }
      if (this.basicInfo.moveMaterialType === 'receive') {
        const params = {
          moveMaterialType: this.basicInfo.moveMaterialType,
          prodorgId: this.basicInfo.officeId,
          locationKind: this.dialogFilters.locationKind,
          locationId: this.dialogFilters.locationId,
          flag: 'Y',
          selectedList: this.selectedDialogRow,
        };
        checkAvailable(params).then(res => {
          if (res.success) {
            this.handleAddRows();
          } else {
            this.$confirm(res.msg, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                this.handleAddRows();
              })
              .catch(e => {});
          }
        });
      } else {
        this.handleAddRows();
      }
    },
    handleAddRows() {
      for (let item of this.selectedDialogRow) {
        let obj = {
          index: this.tableList.length,
          count: 0,
          mtlgroupId: item.mtlgroupId,
          locationKind: item.locationKind,
          originalLocationKind: item.locationKind, // 元未知类型
          originalLocationKindName: item.locationKindName,
          originalLocationId: item.locationId, // 原位置id 非空,
          originalLocationCode: item.locationCode, // 原位置编码 非空,
          originalLocationName: item.locationName, // 原位置名称 非空,
          targetLocationKind: '', // 目标位置类型 非空,
          targetLocationId: '', // 目标位置id 非空,
          targetLocationCode: '', // 目标位置编码 非空,
          targetLocationName: '', // 目标位置名称 非空,
          batchNo: item.mtlgroupNo, // 物料批次号 非空,
          materialId: item.materialId, // 物料ID 非空,
          materialCode: item.materialCode, // 物料编码,
          materialName: item.materialName, // 物料名称,
          materialDesc: item.materialDesc, // 规格型号,
          //2024年8月29日 新增materialBarcode字段，记录料号
          materialBarcode: '',
          oldQty: item.mtlQty, // 原库存数量 非空,
          mtlQty: '', // 数量 非空,
          mtlUom: item.mtlUom, // 计量单位ID 非空,
          mtlUomname: item.mtlUomname, // 计量单位名,
          relateduserId: this.basicInfo.relateduserId ? this.basicInfo.relateduserId : '', // 移料人id 非空,
          relateduserCode: this.basicInfo.relateduserCode ? this.basicInfo.relateduserCode : '', // 移料人编码,
          relateduserName: this.basicInfo.relateduserName ? this.basicInfo.relateduserName : '', // 移料人名称,
          lotcontrolledFlag: item.lotcontrolledFlag, // 批次管理， 物料选择中批次管理字段， Y - 是， N - 否 非空,
          mtlSpy: item.mtlSpy, // SN单位,===============新增===============
          mtlSpyname: item.mtlSpyname, // SN单位名称,===============新增===============
          mtlSpuqty: '', // 序列数量,===============新增===============
          mtlKind: item.mtlKind, // 物料类别,===============新增===============
          mtlKindName: item.mtlKindName,
          serializedFlag: item.serializedFlag, // 序列管理，Y-是，N-否===============新增===============
          targetLocationList: [],
          mpInvActivitySnHtWmsList: [],
          onlyId: item.id,
          claimEqpCode: item.claimEqpCode,
          claimEqpName: item.claimEqpName,
          claimEqpId: item.claimEqpId,
          moveSubQty: '', // 辅助计量单位数量 选填,
          moveWeight: '', // 称重 选填,
          moveConvertRate: '', // 换算率 选填,
        };
        this.tableList.push(obj);
      }
      // 只有一条时，默认选中
      if (this.tableList.length === 1) {
        // console.log('只有一条时，默认选中')
        this.$refs.tableList.setCurrentRow(this.tableList[0], true);
      }
      this.$nextTick(() => {
        this.$refs.tableList.doLayout();
      });
      this.dialogIsShow = false;
    },
    // 打开移料人弹框
    showPeopleDialog(text, index) {
      if (this.basicInfo.officeId === '' || this.basicInfo.officeId === null) {
        this.$message({
          duration: 1500,
          message: '请选择车间',
          type: 'warning',
        });
        return false;
      }
      this.clickType = text;
      if (index !== undefined) {
        this.peopleIndex = index;
      }
      this.dialogPeopleIsShow = true;
      this.selectedPeopleRow = {};
      this.dialogPeople.userCode = '';
      this.dialogPeople.userName = '';
      this.getDialogSelection();
      this.paramsPeople = {
        requestId: uuid(32, 32),
        prodorgId: this.basicInfo.officeId,
        pageSize: this.dialogPeoplePag.pageSize,
        pageNo: this.dialogPeoplePag.pageNo,
        userCode: null,
        userName: null,
      };
      this.queryPeople();
    },
    /**
     * 移料人弹框
     */
    queryPeople() {
      findPeople(this.paramsPeople)
        .then(res => {
          if (res.success === true) {
            // this.dialogPeopleList = res.rows
            this.dialogPeopleList = (res.rows || []).map((item, index) => {
              item.index = index + 1 + (this.dialogPeoplePag.pageNo - 1) * this.dialogPeoplePag.pageSize;
              return item;
            });
            this.dialogPeoplePag.totalRecord = res.count;
            this.$nextTick(_ => {
              this.$refs.singleTable.doLayout();
            });
          }
        })
        .catch(() => {});
    },
    // 移料人查询按钮
    searchPeopleList() {
      this.selectedPeopleRow = {};
      this.dialogPeoplePag.pageNo = 1;
      this.paramsPeople = {
        requestId: uuid(32, 32),
        pageSize: this.dialogPeoplePag.pageSize,
        pageNo: this.dialogPeoplePag.pageNo,
        userCode: this.dialogPeople.userCode,
        userName: this.dialogPeople.userName,
        prodorgId: this.basicInfo.officeId,
      };
      this.queryPeople();
    },
    // 移料弹框单选
    selPeopleRow(val) {
      this.selectedPeopleRow = val;
    },
    // 双击
    dbClickPerson(val) {
      this.selectedPeopleRow = val;
      if (this.clickType === 'clickRow') {
        this.tableList[this.peopleIndex].relateduserName = this.selectedPeopleRow.userName;
        this.tableList[this.peopleIndex].relateduserId = this.selectedPeopleRow.userId;
        this.tableList[this.peopleIndex].relateduserCode = this.selectedPeopleRow.userCode;
      } else {
        this.basicInfo.relateduserName = this.selectedPeopleRow.userName;
        this.basicInfo.relateduserId = this.selectedPeopleRow.userId;
        this.basicInfo.relateduserCode = this.selectedPeopleRow.userCode;
        this.tableList.forEach(item => {
          if (item.relateduserName === '' || item.relateduserName === null) {
            item.relateduserName = this.selectedPeopleRow.userName;
            item.relateduserId = this.selectedPeopleRow.userId;
            item.relateduserCode = this.selectedPeopleRow.userCode;
          }
        });
      }

      this.dialogPeopleIsShow = false;
    },
    // 移料人弹框分页
    getPeopleDialogList(val) {
      this.dialogPeoplePag.pageNo = val;
      this.paramsPeople.pageNo = val;
      this.queryPeople();
    },
    // 移料人保存
    savePeopleVal() {
      if (this.selectedPeopleRow.length === 0) {
        this.$message({
          duration: 1500,
          message: '请选择一条数据',
          type: 'warning',
        });
        return false;
      }
      this.tableList[this.peopleIndex].relateduserName = this.selectedPeopleRow.userName;
      this.tableList[this.peopleIndex].relateduserId = this.selectedPeopleRow.userId;
      this.tableList[this.peopleIndex].relateduserCode = this.selectedPeopleRow.userCode;
      this.dialogPeopleIsShow = false;
    },
    savePeopleForm() {
      if (this.selectedPeopleRow.length === 0) {
        this.$message({
          duration: 1500,
          message: '请选择一条数据',
          type: 'warning',
        });
        return false;
      }
      this.basicInfo.relateduserName = this.selectedPeopleRow.userName;
      this.basicInfo.relateduserId = this.selectedPeopleRow.userId;
      this.basicInfo.relateduserCode = this.selectedPeopleRow.userCode;
      this.tableList.forEach(item => {
        if (item.relateduserName === '' || item.relateduserName === null) {
          item.relateduserName = this.selectedPeopleRow.userName;
          item.relateduserId = this.selectedPeopleRow.userId;
          item.relateduserCode = this.selectedPeopleRow.userCode;
        }
      });
      this.dialogPeopleIsShow = false;
    },
    confirm() {
      this.save('Submit');
    },
    saveInfo() {
      this.save('Save');
    },
    // 保存
    save(type) {


      if(this.basicInfo.orderNo!=""){
        this.$message({
          duration: 1500,
          message: '已提交过领料单，不可重新提交',
          type: 'warning',
        });
        return false;
      }
      this.$refs['basicForm'].validate(valid => {
        if (valid) {
          var mpMtlMoveList = this.tableList;
          // this.dataList = [
          //   ...mpMtlMoveList,
          //   ...this.mpMtlSnHtWmsList
          // ]
          if (mpMtlMoveList.length === 0) {
            this.$message({
              duration: 1500,
              message: '请添加物料上料信息',
              type: 'warning',
            });
            return false;
          }

          if(this.basicInfo.moveMaterialType=='return'){
            if(this.basicInfo.moveMaterialType==''){
              this.$message({
                duration: 1500,
                message: '请选择退料类型',
                type: 'warning',
              });
              return false;
            }
            if(this.basicInfo.moveMaterialReturnAbove==''){
              this.$message({
                duration: 1500,
                message: '请选择退料是超额',
                type: 'warning',
              });
              return false;
            }
          }

          for (let item of mpMtlMoveList) {
            if (item.mtlQty === '' || item.mtlQty === null) {
              this.$message({
                duration: 1500,
                message: '数量不能为空',
                type: 'warning',
              });
              return false;
              // } else if (item.mtlQty !== '' && item.mtlQty !== null && !reg.test(item.mtlQty)) {
              //   this.$message({
              //     message: '数量请输入正整数',
              //     type: 'warning'
              //   })
              //   return false
            } else if (item.mpInvActivitySnHtWmsList.length<1) {
              this.$message({
                duration: 1500,
                message: '物料条码不能为空',
                type: 'warning',
              });
              return false;
            }else if (item.targetLocationKind === '' || item.targetLocationKind === null) {
              this.$message({
                duration: 1500,
                message: '目标位置类型不能为空',
                type: 'warning',
              });
              return false;
            }
            else if((this.basicInfo.moveMaterialType=='return')&&(item.targetLocationKind!='WINV')){
              this.$message({
                duration: 1500,
                message: '生产退还，目标位置必须是线边仓。',
                type: 'warning',
              });
              return false;
            } else if ((this.basicInfo.moveMaterialReturnAbove!='Y')&&(parseInt(item.mtlQty) > parseInt(item.oldQty) || item.mtlQty > item.oldQty)) {

              this.$message({
                duration: 1500,
                message: '没有选择生产退还的【超额】，移料数量不能大于数量',
                type: 'warning',
              });
              return false;

            } else if (!item.mtlQty || item.mtlQty <= 0) {
              this.$message({
                duration: 1500,
                message: '移料数量不得小于等于0',
                type: 'warning',
              });
              return false;
            } else if (item.targetLocationId === '' || item.targetLocationId === null) {
              this.$message({
                duration: 1500,
                message: '目标位置不能为空',
                type: 'warning',
              });
              return false;
            } else if (item.targetLocationId === item.originalLocationId) {
              this.$message({
                duration: 1500,
                message: '目标位置不能与原位置相同',
                type: 'warning',
              });
              return false;
            } else if (item.relateduserName === '' || item.relateduserName === null) {
              this.$message({
                duration: 1500,
                message: '移料人不能为空',
                type: 'warning',
              });
              return false;
            }

            // let arr = [];
            // let errMsg = '';
            // if (item.mpInvActivitySnHtWmsList) {
            //   item.mpInvActivitySnHtWmsList.forEach(sn => {
            //     // if (sn.selFlag === '1') {
            //     // 工作中心
            //     if (item.targetLocationKind === 'MWC') {
            //       if (sn.activeFlag === 'Y' && sn.materialState === 'Normal') {
            //         arr.push(sn);
            //       } else {
            //         errMsg = '仅状态为启用且正常的序列号才得移至工作中心';
            //         return false;
            //       }
            //     } else {
            //       arr.push(sn);
            //     }
            //     // }
            //   });
            // }
            // if (errMsg) {
            //   this.$message({
            //     duration: 1500,
            //     message: errMsg,
            //     type: 'warning',
            //   });
            //   return false;
            // }
            // item.mpInvActivitySnHtWmsList = arr;
          }

          mpMtlMoveList.forEach(item => {
            item.mtlSpuqty = item.mtlSpuqty ? item.mtlSpuqty : 0;
          });
          this.loadingTree = true;
          let param = {
            id: this.$route.query.id || '',
            activityTime: this.basicInfo.activityTime, // 移料日期
            prodorgId: this.basicInfo.officeId, // 车间ID
            prodorgCode: this.prodorgCode, // 车间编号
            prodorgName: this.prodorgName, // 车间名称
            mpMtlMoveList: mpMtlMoveList,
            operatorType: type,
            // 新增
            deptId: this.basicInfo.deptId,
            deptCode: this.basicInfo.deptCode,
            deptName: this.basicInfo.deptName,
            recTypeId: this.basicInfo.recTypeId,
            recTypeCode: this.basicInfo.recTypeCode,
            recTypeName: this.basicInfo.recTypeName,
            ruleId: this.basicInfo.ruleId,

            moveMaterialType: this.basicInfo.moveMaterialType,
            moveMaterialSource: this.basicInfo.moveMaterialSource,
            sourceNo: this.basicInfo.sourceNo,
            remarks: this.basicInfo.remarks,

            applicantId: this.basicInfo.applicantId,

            moveMaterialTypeReturn: this.basicInfo.moveMaterialTypeReturn,

            //事务操作人员
            opuserId: this.basicInfo.relateduserId ,
            opuserName:    this.basicInfo.relateduserName ,
            // relateduserId: this.basicInfo.relateduserId ,
            opuserCode:  this.basicInfo.relateduserCode,



            //补充WMS-线边仓仓库编码
            issueWarehouse:this.basicInfo.issueWarehouse,
            issueWarehouseName:this.basicInfo.issueWarehouseName,
            issueWarehouseU8:  this.basicInfo.issueWarehouseU8,
            //补充WMS-车间编码-货位编码
            receiveWc:this.basicInfo.receiveWc,
            receiveWcName:this.basicInfo.receiveWcName,
            orderCode:this.basicInfo.sourceNoInfo.orderCode,
            productQty:this.basicInfo.sourceNoInfo.dieQty,
            locationKind:this.basicInfo.targetLocationKind,
            locationId:this.basicInfo.targetLocationId,
            locationCode:this.basicInfo.targetLocationCode,
            locationName:this.basicInfo.targetLocationName,
            htWmsStatus:2
          };

          console.log(param,'saveInfo-param');

          saveInfo(param)
            .then(res => {
              this.loadingTree = false;
              if (res.success === true) {
                this.$message.success({
                  message: res.msg,
                });
                if (type === 'Submit') {
                  this.$router.push({
                    name: 'moveInfoHtModule',
                    query: {
                      view: true,
                      id: res.id || '',
                    },
                  });
                  this.selectionData = {};
                  this.templateList = [];
                  this.initInfo();
                } else {
                  this.$router.push({
                    name: 'moveInfoHtModule',
                    query: {
                      id: res.id || '',
                      type: 'edit',
                    },
                  });
                  this.selectionData = {};
                  this.templateList = [];
                  this.initInfo();

                  // this.basicInfo.htWmsStatus = 2;
                }
                // this.back()
              }
            })
            .catch(() => {
              this.loadingTree = false;
            });
        }
      });
    },
    /**
     * @name:deleteRow
     * @description:默认标准删除行
     * @param {type}:
     */
    deleteRow(index, rows) {
      console.log(index);
      let snArr = [];
      const copyTableArr = _.cloneDeep(this.tableList);
      let list = copyTableArr[index].mpInvActivitySnHtWmsList || [];
      list.forEach((item, itemIndex) => {
        snArr.push(item.materialBarcode);
      });
      this.$confirm('确认删除选中的数据？')
        .then(_ => {
          // 清空序列
          this.mpMtlSnHtWmsList = [];
          // 处理序列集合
          this.mtlSnArr = this.mtlSnArr.filter(function (item) {
            return snArr.indexOf(item) == -1;
          });

          this.tableList.splice(index, 1);
          // 只有一条时，默认选中
          if (this.tableList.length !== 0) {
            this.$refs.tableList.setCurrentRow(this.tableList[0]);
            this.nowIndex = 0;
          }
        })
        .catch(_ => {});
    },
    /**
     * @name:backRow
     * @description:默认标准恢复行
     * @param {type}:
     */
    backRow(index, rows) {
      if (rows[index].delFlag === '1') {
        rows[index].delFlag = '0';
      }
    },
    // 序列多选
    selSnRow(val) {
      if (this.selectionData.serializedFlag !== 'Y') {
        return;
      }
      this.selectionData.mpInvActivitySnHtWmsList = _.cloneDeep(val);
      let count = 0;
      this.selectionData.mpInvActivitySnHtWmsList.forEach(item => {
        let x = new Decimal(count);
        let y = new Decimal(item.materialQty);
        count = Number(x.plus(y).toFixed(8));
      });
      this.selectionData.mtlQty = count;
      this.selectionData.mtlSpuqty = this.selectionData.mpInvActivitySnHtWmsList.length;
      // if (!this.selectedRowSn.includes(val)) {
      //   this.selectedSnRow = val
      //   let qty = 0
      //   let line = 0
      //   let arr = (this.tableList[this.nowIndex].mpInvActivitySnHtWmsList || []).map(item => {
      //     if (val.includes(item)) {
      //       item.selFlag = '1'
      //       qty = this.calculNum('add', qty, item.materialQty)
      //       line++
      //     } else {
      //       item.selFlag = '0'
      //     }
      //     return item
      //   })
      //   this.tableList[this.nowIndex].mpInvActivitySnHtWmsList = arr
      //   this.tableList[this.nowIndex].mtlQty = qty === 0 ? '' : qty
      //   this.tableList[this.nowIndex].mtlSpuqty = line === 0 ? '' : line
      // }
    },

    /**
     * @name:setHeight
     * @description:设置表格高度
     * @param {type}:
     */
    setHeight() {
      setTimeout(() => {
        this.listHeight = $('.js-main').height() - $('.js-form1').height() - $('.js-form2').height() - 160;
        // 监听窗口大小变化
        let self = this;
        window.onresize = () => {
          self.tableHeight = $('.js-main').height() - $('.js-form1').height() - $('.js-form2').height() - 160;
        };
      }, 100);
    },
    // 单据类型新增start
    showItemDialog() {
      // this.$refs.itemTypeDialog.showDialog('MoveMaterial');
    },
    saveItemVal(data) {
      this.basicInfo.recTypeId = data.id;
      this.basicInfo.ruleId = data.ruleId;
      this.basicInfo.recTypeName = data.typeName;
      this.basicInfo.recTypeCode = data.typeCode;

    },
    saveItemFormTypeVal() {
      if(this.basicInfo.recTypeName==""){
        let param = {
          requestId: uuid(32, 32),
          typeCode: 'CJYLD_03',
        };
        getInfoByTypeCode(param)
            .then(res => {
              if (res.success) {
                if (!res.data) {
                  this.$message.warning({
                    message: '请先配置单据类型-编码规则，并启用',
                    duration: 1500,
                  });
                  return;
                }
                this.basicInfo.recTypeId = res.data.id;
                this.basicInfo.recTypeName = res.data.typeName;
                this.basicInfo.ruleId = res.data.ruleId;
                this.basicInfo.recTypeCode = res.data.typeCode;
              }
            })
            .catch(() => {});
      }

    },
    getDefaultType() {


      //单据类型-车间领料申请单
      this.saveItemFormTypeVal();

      // let param = {
      //   requestId: uuid(32, 32),
      //   formKind: 'MoveMaterial',
      // };
      // getDefaultType(param)
      //   .then(res => {
      //     if (res.success) {
      //       if (!res.formType) {
      //         this.$message.warning({
      //           message: '请先配置单据类型-编码规则，并启用',
      //           duration: 1500,
      //         });
      //         return;
      //       }
      //       this.basicInfo.recTypeId = res.formType.id;
      //       this.basicInfo.recTypeName = res.formType.typeName;
      //       this.basicInfo.ruleId = res.formType.ruleId;
      //       this.basicInfo.recTypeCode = res.formType.typeCode;
      //     }
      //   })
      //   .catch(() => {});
    },
    getDeptList() {
      let param = {};
      getDeptList(param)
        .then(res => {
          if (res.success) {
            // if (res.deptList.length <= 0 || !res.deptList) {
            //   this.$message.warning({
            //     message: '您的帐号没有配置开立部门，请先配置'
            //   })
            //   return
            // }
            this.deptSel = res.deptList;
            if (res.deptList.length === 1) {
              this.basicInfo.deptId = res.deptList[0].deptId;
              this.basicInfo.deptName = res.deptList[0].deptName;
              this.basicInfo.deptCode = res.deptList[0].deptCode;
            }
            if (!this.basicInfo.id) {
              this.getDefaultType();
            }
          }
        })
        .catch(() => {});
    },
    changeDept(id) {
      if (!id) {
        return;
      }
      this.deptSel.forEach(item => {
        if (id === item.deptId) {
          this.basicInfo.deptName = item.deptName;
          this.basicInfo.deptCode = item.deptCode;
        }
      });
    },
    // 单据类型新增end
    // 判定是否可选
    calcSelectStatus(row) {

      //ezio 必选
      return true;

      let flag = true;
      let kind = this.selectionData.targetLocationKind === 'MWC';
      if (kind) {
        if (row.activeFlag === 'Y' && row.materialState === 'Normal') {
          flag = true;
        } else {
          flag = false;
        }
      }
      return flag;
    },
    // 小数点加减
    calculNum(type, num1, num2) {
      var sq1, sq2, m;
      try {
        sq1 = num1.toString().split('.')[1].length;
      } catch (e) {
        sq1 = 0;
      }
      try {
        sq2 = num2.toString().split('.')[1].length;
      } catch (e) {
        sq2 = 0;
      }
      m = Math.pow(10, Math.max(sq1, sq2));
      return type == 'add' ? (num1 * m + num2 * m) / m : (num1 * m - num2 * m) / m;
    },
    initInfo() {
      let params = {
        id: this.$route.query.id || '',
      };
      initPage(params).then(res => {
        if (res.success) {
          this.factoryArr = res.companyList; // 车间列表
          //限制车间列表的显示
          let proNeedList = ['D61','D62','D63'];
          this.factoryArr = this.factoryArr.filter(item => proNeedList.indexOf(item.officeCode)>-1);
          this.factoryArr.sort((a, b) => a.officeCode.substr(1,2) - b.officeCode.substr(1,2));

          this.locationTypeArr = res.locationKindList; // 目标位置类型
          this.locationTypeArrHtWms =  res.locationKindList;
          // this.formLocationTypeArr = res.locationKindList // 位置类型

          if (res.mpInvActivity && res.mpInvActivity !== null) {
            this.basicInfo.officeId = res.mpInvActivity.prodorgId;
            this.basicInfo.deptId = res.mpInvActivity.deptId;
            this.basicInfo.deptCode = res.mpInvActivity.deptCode;
            this.basicInfo.deptName = res.mpInvActivity.deptName;
            this.basicInfo.recTypeId = res.mpInvActivity.recTypeId;
            this.basicInfo.recTypeCode = res.mpInvActivity.recTypeCode;
            this.basicInfo.recTypeName = res.mpInvActivity.recTypeName;
            this.basicInfo.orderStatus = res.mpInvActivity.orderStatus;
            this.basicInfo.moveMaterialType = res.mpInvActivity.moveMaterialType;
            this.basicInfo.moveMaterialSource = res.mpInvActivity.moveMaterialSource;
            this.basicInfo.sourceNo = res.mpInvActivity.sourceNo;
            this.basicInfo.remarks = res.mpInvActivity.remarks;
            this.basicInfo.orderNo = res.mpInvActivity.orderNo;
            this.basicInfo.applicant = res.mpInvActivity.applicant;
            this.basicInfo.applicantId = res.mpInvActivity.applicantId;

            this.basicInfo.moveMaterialTypeReturn = res.mpInvActivity.moveMaterialTypeReturn;
            this.basicInfo.moveMaterialReturnAbove = res.mpInvActivity.moveMaterialReturnAbove;

            this.basicInfo.issueWarehouse = res.mpInvActivity.issueWarehouse;
            this.basicInfo.issueWarehouseName = res.mpInvActivity.issueWarehouseName;
            this.basicInfo.receiveWc = res.mpInvActivity.receiveWc;
            this.basicInfo.receiveWcName = res.mpInvActivity.receiveWcName;
            this.basicInfo.htWmsStatus = res.mpInvActivity.htWmsStatus;

            this.basicInfo.relateduserId = res.mpInvActivity.opuserId;
            this.basicInfo.relateduserName = res.mpInvActivity.opuserName;
            this.basicInfo.relateduserCode = res.mpInvActivity.opuserCode;



            this.tableList = res.mpInvActivity.mpMtlMoveList || [];
            let mtlArr = [];
            this.tableList.forEach((item, index) => {
              console.log(item);
              item.targetLocationList = [];
              item.index = index;
              // 批次号
              mtlArr.push({
                mtlgroupNo: item.batchNo,
                locationId: item.originalLocationId,
                mtlKind: item.mtlKind,
              });
            });
            // 获取最新数量
            if (!this.$route.query.view) {
              this.getNewQty(mtlArr);
            }
            this.getLocation();
            // 车间
            for (let item of this.factoryArr) {
              if (this.basicInfo.officeId === item.id) {
                this.prodorgCode = item.officeCode;
                this.prodorgName = item.officeName;
              }
            }

            //BOM对应的仓库物料信息
            if(this.prodorgCode!=''&&(this.basicInfo.issueWarehouse==undefined ||this.basicInfo.issueWarehouse=="" )){
              this.getDataByByProdorgCode(this.prodorgCode);
            }

            //标签-控制按钮
            this.getDisabledItemsChange();

            //整体目标列表
            this.onSelectTargetBasic();


            //后置赋值
            this.basicInfo.targetLocationKind = res.mpInvActivity.locationKind;
            this.basicInfo.targetLocationId = res.mpInvActivity.locationId;
            this.basicInfo.targetLocationCode = res.mpInvActivity.locationCode;
            this.basicInfo.targetLocationName = res.mpInvActivity.locationName;

            //流程卡信息
            this.basicInfo.sourceNoInfo = {
              lotNo:'',
              orderCode:'',
              dieQty:'',
            }

          }


        }
      });
    },
    async getLocation() {
      for (let item of this.tableList) {
        if (this.basicInfo.officeId && item.targetLocationKind) {
          let param = {
            updateFlag: 'true', // 修改标识，true-修改页面，false-首页，当为true时车间id不能为空 非空,
            prodorgId: this.basicInfo.officeId, // 车间id,
            locationKind: item.targetLocationKind, // 位置类型 WINV-线边仓，MWC-工作中心 非空,
          };

          let res = await getBySelection(param);
          if (res.success) {
            if (item.targetLocationKind === 'WINV') {
              for (let locItem of res.allLocList) {
                let obj = {
                  id: locItem.id,
                  code: locItem.locationCode,
                  name: locItem.locationName,
                };
                item.targetLocationList.push(obj);
              }
              // console.log(row.targetLocationList)
            } else {
              for (let locItem of res.workcenterList) {
                let obj = {
                  id: locItem.id,
                  code: locItem.workcenterCode,
                  name: locItem.workcenterName,
                };
                item.targetLocationList.push(obj);
              }
              // console.log(row.targetLocationList)
            }
          }
        }
      }
      this.tableList = [...this.tableList];
    },
    setTableHeight() {
      const height = this.$refs.infoPage.offsetHeight - this.$refs.formPanel.offsetHeight - 164;
      this.listHeight = height < 200 ? 200 : height;
    },
    // 选择禁用
    selectInit(row) {
      let flag = true;
      if (this.tableList.length >= 1) {
        this.tableList.forEach(item => {
          if (row.mtlgroupNo === item.batchNo) {
            flag = false;
          }
        });
      }
      return flag;
    },
    insertNum(row, index,type) {


      //称重或换算率
      if(type>1){

        if(row.moveConvertRate>0&&row.moveWeight>0){
          // row.mtlQty = (row.moveConvertRate*row.moveWeight).toFixed(2);
          row.mtlQty = (row.moveConvertRate*row.moveWeight).toFixed(0);
        }
        else{
          return true;
        }
      }
      else{
        //数量手动填写-换手率清理为空
        this.tableList[index].moveConvertRate = '';
        this.tableList[index].moveWeight = '';

        //ezio  2025-04-19 按BOM换算率计算
        this.tableList[index].mtlQty =  this.changeRateQty(row.changeRateNew, row.mtlQty);

      }


       if(this.basicInfo.moveMaterialType!='return'){
         this.basicInfo.moveMaterialReturnAbove = 'N';
       }
      //2024-12-21 工作中心移到线边仓时，是生产退还的允许移料数量>总数量
      //不能有其他目标位置不是线边仓的记录
      if(this.basicInfo.moveMaterialType=='return'){

        let location_mwc_index_org = this.tableList.findIndex(f => f.originalLocationKind === 'WINV');
        if(location_mwc_index_org>-1 ){
          this.$message.error('生产退还不能原位置是线边仓的，应是工作中心的。');
          this.tableList[index].mtlQty = '';
          this.tableList[index].moveWeight = '';
          return false;
        }
        let location_mwc_index = this.tableList.findIndex(f => f.targetLocationKind === 'MWC');
        let location_mwc_null_index = this.tableList.findIndex(f => f.targetLocationKind =='');
        if(location_mwc_index>-1 || location_mwc_null_index>-1 ){
          this.$message.error('生产退还需要先选择目标位置 且目标位置是线边仓。');
          this.tableList[index].mtlQty = '';
          this.tableList[index].moveWeight = '';
          return false;
        }
      }



      // this.tableList[index].mtlQty = row.mtlQty.replace(/[^\d.]/g, '');
      this.tableList[index].mtlQty = row.mtlQty;
      if (row.mtlQty > row.oldQty) {

        //2024-12-21 工作中心移到线边仓时，是生产退还的允许移料数量>总数量
        // console.log('insertNum',row);
        // console.log('moveMaterialType',this.basicInfo.moveMaterialType);
        if((this.basicInfo.moveMaterialType=='return')&& (row.originalLocationKind=='MWC')&&(row.targetLocationKind=='WINV')){

          if(this.basicInfo.moveMaterialReturnAbove!='Y'){
            this.$message.error('除了选择生产退还，【退料是否超额】必须选【超额】，不然不允许移料数量大于总数量');
            this.tableList[index].mtlQty = '';
            this.tableList[index].moveWeight = '';
            return false;
          }
          else{
            this.$message.warning('移料数量已大于总数量，由于是生产退还允许本操作，请郑重校验数据。');
          }

        }
        else{
          this.$message.error('移料数量不能大于总数量');
          this.tableList[index].mtlQty = '';
          this.tableList[index].moveWeight = '';
        }


      }

    },
    // 获取最新数量
    async getNewQty(mtlSn) {
      let param = {
        mpInvMtlLocList: mtlSn,
      };
      let res = await getNewQty(param);
      if (res.success) {
        this.tableList.forEach(async mtl => {
          let snArr = await (mtl.mpInvActivitySnHtWmsList || []).map(sn => {
            return sn.materialBarcode;
          });
          res.mpInvMtlLocList.forEach(item => {
            if (item.mtlgroupNo === mtl.batchNo) {
              // 数量
              mtl.oldQty = item.mtlQty;
              if (mtl.serializedFlag === 'Y') {
                // 序列号存在时，移库数量相加
                mtl.mtlQty = 0;
                if (item.mpInvMtlLocSnList && item.mpInvMtlLocSnList.length >= 1) {
                  item.mpInvMtlLocSnList.forEach(mtlSn => {
                    if (snArr.includes(mtlSn.materialBarcode)) {
                      mtl.mtlQty += mtlSn.mtlQty;
                    }
                    // 序列号的状态
                    mtl.mpInvActivitySnHtWmsList.forEach(mpSn => {
                      if (mpSn.materialBarcode === mtlSn.materialBarcode) {
                        mpSn.activeFlag = mtlSn.activeFlag;
                        mpSn.materialState = mtlSn.materialState;
                      }
                    });
                  });
                }
              }
            }
          });
        });
      }
    },
    handleClearDialog() {
      this.basicInfo.recTypeId = '';
      this.basicInfo.ruleId = '';
      this.basicInfo.recTypeName = '';
      this.basicInfo.recTypeCode = '';
    },
    //扫描移料来源单号
    handleScan() {
      //查询WMS线边仓的库存信息
      console.log(this.basicInfo,'handleScan-this.basicInfo');
      if(this.prodorgCode==''){
        this.$message.warning('请选择车间');
        return false;
      }
      //BOM对应的仓库物料信息
      if(this.prodorgCode!=''&&(this.basicInfo.issueWarehouse==undefined ||this.basicInfo.issueWarehouse=="" )){
        this.getDataByByProdorgCode(this.prodorgCode);
      }
      //已开始扫码后不可再修改流程卡
      if(this.tableList.length>0){
        this.$message.warning('不能重复扫描或修改流程卡，除非删除全部物料记录。');
      }

      //查询生产订单对应的生产订单号
      if(this.basicInfo.sourceNo!=""){

        let param = {
          requestId: uuid(32, 32),
          orderCode: this.basicInfo.sourceNo,
          opType: 2,
        };

        findMoveWmsListbyOrder(param)
            .then(res => {
              console.log(res,'handleScan-res');
              if(res.success){
                if(!res.data){
                  this.$message.warning('提示：生产订单不存在。');
                  return false;
                }
                if(res.data==undefined){
                  this.$message.warning('提示：获取生产订单失败。');
                  return false;
                }

                //生产订单 Y已完成,C已撤销，H已结批暂停，不能再领料

                if(res.data.mtlList!==undefined){
                  let statusList = ['Y','C','H'];
                  if(statusList.indexOf(res.data.orderStatus)>-1){
                    this.$message.warning('提示：生产订单已结束，不可领料。');
                    return false;
                  }
                  this.orderReveivedList = res.data.mtlList;
                }


                this.basicInfo.sourceNoInfo = {
                  lotNo:'',
                  orderCode:res.data.orderCode,
                  dieQty:res.data.productQty,
                }
                console.log(this.orderReveivedList,'this.orderReveivedList ');
                console.log(this.basicInfo.sourceNoInfo,'this.basicInfo.sourceNoInfo');
                //生产订单对应的BOM查询
                this.fetchBom();


                this.isDisableStatus = true;
                this.$message({
                  duration: 500,
                  message: '提示：生产订单扫描完成。',
                  type: 'warning',
                });
                return true;
              }
              else{
                this.isDisableStatus = false;
                this.$message.warning('提示：'+res.message);
                return false;
              }

            });

      }




    },
    // 枚举
    async handleGetEnum() {
      let res = await getEnum({
        ids: ['MOVE_MATERIAL_TYPE', 'MOVE_MATERIAL_SOURCE','MOVE_MATERIAL_TYPE_RETURN'],
      });
      if (res.success) {
        this.moveMaterialTypeList = res.data['MOVE_MATERIAL_TYPE']; //移料类别

        //生产领用
        this.moveMaterialTypeList = this.moveMaterialTypeList.filter(item => item.value=="receive");

        this.moveMaterialSourceList = res.data['MOVE_MATERIAL_SOURCE']; //移料来源
        //生产批
        this.moveMaterialSourceList = this.moveMaterialSourceList.filter(item => item.value=="orderCode");

        this.moveMaterialTypeReturnList = res.data['MOVE_MATERIAL_TYPE_RETURN']; //移料类别-退料类型
      }
    },


    //移料类型不同处理数据
    dealDataByMaterialType(type){

      if(this.basicInfo.moveMaterialType!='return'){
        this.tableList.forEach(item => {

          item.moveSubQty ='';
          item.moveWeight ='';
          item.moveConvertRate ='';
        });
      }
    },
    //车间判断指定的领料仓库
     getDataByByProdorgCode(prodorgCode)
    {

      console.log(prodorgCode,'prodorgCode');
      console.log( this.receiveWcList,'getDataByByProdorgCode-receiveWcList');
      this.receiveWcList.some(item => {
        if (item.prodorgCode == prodorgCode) {
          this.basicInfo.receiveWc = item.value;
          this.basicInfo.receiveWcName = item.label;
          return true;
        }
      })

      this.issueWarehouseList.some(item2 => {
        if (item2.prodorgCode == prodorgCode) {
          this.basicInfo.issueWarehouse = item2.value;
          this.basicInfo.issueWarehouseName = item2.label;
          this.basicInfo.issueWarehouseU8 = item2.u8HouseCode;
          return true;
        }
      });



    },

    //按生产订单号获取BOM
    fetchBom()
    {
      // BOM处理逻辑...
      let param = {
        requestId: uuid(32, 32),
        orderCode: this.basicInfo.sourceNoInfo.orderCode,
        whCode: this.basicInfo.issueWarehouseU8,//发料仓库
        wipType: 1,//工序倒冲的物料
        // wcCode: this.basicInfo.receiveWc,
      };

      // console.log(this.basicInfo,'fetchBom-basicInfo');

      if(this.basicInfo.issueWarehouse==""){
        this.$message.warning('提示：请选择车间，没有对应的U8车间！');
        return false;
      }
      else if(this.basicInfo.receiveWc==""){
        this.$message.warning('提示：请选择车间，没有对应的U8发料仓库！');
        return false;
      }

      console.log(param,'getOrderBOM-param');
      getOrderBOM(param)
          .then(res => {
            console.log(res, 'getOrderBOM-res');
            if (res.status == 200) {

              let bomList = res.data;

              if (bomList.length < 1) {
                this.$message.warning('提示：该订单没有查到该条件的BOM！');
                return false;
              }


              //车间按生产订单领料-不累计
              this.bomList = [];
              this.orderBomOrgList = [];


              //按生产数量补充 计划用量

              //第一次写入
              bomList.forEach(bomItem => {
                //是否新增
                let filterInfo = this.bomList.find(item => item.materialCode === bomItem.materialCode);
                console.log(filterInfo, "this.bomList.filter");

                // let orderBomQtyItem = Math.round((bomItem.usage * this.newOrder.orderQty) * 1000000) / 1000000;
                let orderBomQtyItem = 0;
                //todo 同个物料-换算率有可能不同
                let changeRateNewItem =this.changeNumberHt(bomItem.changeRate) ;
                // let orderMaterialQtyItem = 0;
                //累计已领
                // let orderMaterialUsedQtyItem = bomItem.usedQty ? Math.round(bomItem.usedQty * 1000000) / 1000000 : 0;
                //已领数量-使用MES数量
                let receiveInfo = this.orderReveivedList.find(item => item.materialCode === bomItem.materialCode);

                let orderMaterialUsedQtyItem = 0;
                if(receiveInfo!==undefined){
                  orderMaterialUsedQtyItem = this.changeNumberHt(receiveInfo.sumMtlQty);
                }

                let planQtyItem = this.changeNumberHt(bomItem.planQty);//可以按订单获取，当前BOM获取也可以
                let htChecked = false;

                //每个物料数量
                let orderMaterialQty = 0;
                let orderMaterialUsedQty = 0;
                let orderMaterialNeedQty = 0;
                let planQty = 0;
                let orderBomQty = 0;
                let usedQty = 0;

                let index = this.bomList.findIndex(item => item.materialCode === bomItem.materialCode);
                // console.log(index, "this.bomList.index");
                // console.log(bomItem, "this.bomList.bomItem");

                //记录订单的物料明细情况
                this.orderBomOrgList.push({
                  ...bomItem,
                  orderBomQty: orderBomQtyItem,
                  orderMaterialUsedQty: orderMaterialUsedQtyItem,
                  changeRateNew: changeRateNewItem,
                  orderMaterialQty: orderMaterialQty,
                  orderMaterialNeedQty: orderMaterialNeedQty,
                  htChecked: htChecked
                });


                if (index == -1) {
                  //按换算率计算-向上取整
                  orderMaterialQty = this.changeRateQty(changeRateNewItem, orderBomQtyItem);
                  //todo 剩余可领
                  orderMaterialNeedQty = this.changeNumberHt(planQtyItem - orderMaterialQty - orderMaterialUsedQtyItem);

                  //没有换算率，值=0 不能打印领用
                  if (orderMaterialQty == 0) {
                    htChecked = false;
                  } else {
                    htChecked = true;
                  }

                  let bom_len = this.bomList.length;
                  this.bomList.push({
                    ...bomItem,
                    orderBomQty: orderBomQtyItem,
                    orderMaterialQty: orderMaterialQty,
                    orderMaterialUsedQty: orderMaterialUsedQtyItem,
                    orderMaterialNeedQty: orderMaterialNeedQty,
                    changeRateNew: changeRateNewItem,
                    htChecked: htChecked,
                  });
                } else {


                  // 理论用量
                  orderBomQty = this.changeNumberHt(filterInfo.orderBomQty+orderBomQtyItem);
                  //计算理论使用总量
                  planQty = this.changeNumberHt(filterInfo.planQty) + planQtyItem;
                  usedQty = this.changeNumberHt(filterInfo.usedQty) + orderMaterialUsedQtyItem;

                  //按换算率计算-向上取整
                  orderMaterialQty = this.changeRateQty(changeRateNewItem, orderBomQty);
                  //todo 累计已领 需要查询新MES的数量,临时使用U8
                  orderMaterialUsedQty = this.changeNumberHt(filterInfo.orderMaterialUsedQty) + orderMaterialUsedQtyItem;
                  //todo 剩余可领
                  // console.log(planQty, 'planQty');
                  // console.log(orderMaterialQty, 'orderMaterialQty');
                  // console.log(orderMaterialUsedQty, 'orderMaterialUsedQty');
                  // console.log(filterInfo.orderMaterialNeedQty, 'filterInfo-orderMaterialNeedQty');
                  orderMaterialNeedQty = this.changeNumberHt(planQty - orderMaterialQty - orderMaterialUsedQty);


                  this.$set(this.bomList, index, {
                    ...filterInfo,
                    orderBomQty: orderBomQty,
                    orderMaterialQty: orderMaterialQty,
                    orderMaterialUsedQty: orderMaterialUsedQty,
                    orderMaterialNeedQty: orderMaterialNeedQty,
                    planQty: planQty,
                    usedQty: usedQty,
                    changeRateNew: changeRateNewItem
                  });

                }



              });


              console.log(this.bomList, 'this.bomList');


              //   初始化赋值列、表数据
              // if (this.initColumns) {
              //     this.originHeaders = _.cloneDeep(this.headerList);
              //     this.initColumns = false;
              // }
              // this.$nextTick(_ => {
              //     this.$refs.mainTable.doLayout();
              // });
            } else {
              this.$message.warning('提示：' + res.massage);
              return false;
            }
          })
          .catch(error => {

            console.log(error, 'getOrderBOM-error');
            this.$message.error('提示：BOM信息查询异常，请联系IT。');
            return false;
          });

    },
    //保留10位小数
    changeNumberHt(num)
    {
      return Math.round((num) * 10000000000) / 10000000000;
    },
    //换算率计算物料数量
    changeRateQty(changeRateNewItem, orderBomQty)
    {
      //按换算率计算-向上取整
      let orderMaterialQty = 0;
      if (changeRateNewItem != null && (changeRateNewItem > 0)) {
        orderMaterialQty = Math.ceil(orderBomQty / changeRateNewItem) * changeRateNewItem;
      }
      return orderMaterialQty;
    },

    //数据全部重置
    reSetData(){
      if(this.tableList.length==0){
        this.isDisableStatus = false;
        this.tableList = []; //物料列表
        this.bomList = []; //批次的BOM列表
        this.mtlSnArr = [];//物料条码列表
        this.mpMtlSnHtWmsList = [];//当前选择物料的物料条码列表

      }

    },
    getDisabledItemsChange(){
      let disableItems = [];
      // if (this.$route.query.view) {
      //   disableItems.push('confirm', 'save');
      // }
      if (!this.printDisable) {
        disableItems.push('confirm', 'save');
      }
      if (this.printDisable) {
        disableItems.push('print');
      }

      return disableItems;

    },
    //获取WMS的仓库列表信息
    fetchHouseList()
    {
      let param = {
        requestId: uuid(32, 32),
        WHADDRESS:''//仓库类别
        // wcCode: this.basicInfo.receiveWc,//领料车间
      };
      getHtWmsHouseList(param)
          .then(res => {
            console.log(res, 'getHtWmsHouseList-res');
            if (res.status == 200) {

              let htWmsWarehouseList = res.data;

              if (htWmsWarehouseList.length < 1) {
                this.$message.warning('提示：WMS仓库列表采集失败！');
                return false;
              }
              this.htWmsWarehouseList= [];
              // 领料仓库列表=WMS线边仓
              // this.receiveWarehouseList = [];
              // 发料仓库列表=主材
              this.issueWarehouseList = [];
              htWmsWarehouseList.forEach(item=>{

                if( item.WHADDRESS=="线边仓"){
                  this.issueWarehouseList.push({
                    label:item.WHNAME,
                    value:item.ID,
                    u8HouseCode:item.WHPERSON,
                    prodorgCode:this.getProdorgCode(item.WHPERSON)
                  })
                }

                this.htWmsWarehouseList.push({
                  ...item,
                  label:item.WHNAME,
                  value:item.ID,
                  u8HouseCode:item.WHPERSON,
                  prodorgCode:this.getProdorgCode(item.WHPERSON)
                });

              })


              console.log(this.issueWarehouseList, 'this.basicInfo.issueWarehouseList');
              console.log(this.htWmsWarehouseList, 'this.basicInfo.htWmsWarehouseList');


              //   初始化赋值列、表数据
              // this.$nextTick(_ => {
              //     this.$refs.mainTable.doLayout();
              // });
            } else {
              this.$message.warning('提示：' + res.massage);
              return false;
            }
          })
          .catch(error => {

            console.log(error, 'getHtWmsHouseList-error');
            this.$message.error('提示：WMS仓库查询异常，请联系IT。');
            return false;
          });

    },
    //对照-线边仓对照MES车间
    getProdorgCode(u8HouseCode){
      if(u8HouseCode=="B02" || u8HouseCode=="PCFE01" ){
         return 'D61';
      }
      else   if(u8HouseCode=="B03" || u8HouseCode=='PCBE01'){
        return 'D62';
      }
      else   if(u8HouseCode=="B05"){
        return 'D63';
      }

      return 'D61';
    },

    /**
     * @name:deleteRowCode
     * @description:默认删除物料条码
     * @param {type}:
     */
    deleteRowCode(childIndex){

      let index = this.nowIndex;//左侧物料的所在行
      console.log(index,'deleteRowCode');
      console.log(childIndex,'deleteRowCode-childIndex');

      let snArr = [];
      const copyTableArr = _.cloneDeep(this.tableList);
      let list = copyTableArr[index].mpInvActivitySnHtWmsList || [];

      let childInfo = this.mpMtlSnHtWmsList[childIndex];
      let childQty = parseFloat(childInfo.materialQty);
      // console.log(childInfo,'deleteRowCode-childInfo');


      snArr.push(childInfo.materialBarcode);

      //物料只有一个条码,需删除左侧物料记录
      if(list.length==1){
        this.deleteRow(index,copyTableArr[index]);
      }
      else{

        //物料条码多个
        this.$confirm('确认删除选中'+childInfo.materialBarcode+'的数据？')
            .then(_ => {

              //删除一个
              this.mpMtlSnHtWmsList = this.mpMtlSnHtWmsList.filter(function (itemSn) {
                return snArr.indexOf(itemSn.materialBarcode) == -1;
              });
              //更新物料对应的数量
              let mtlQty = this.tableList[index].mtlQty-childQty;
              //可领-移料数量
              let orderMaterialNeedQty = this.tableList[index].orderMaterialNeedQty+childQty;
              // 处理序列集合
              this.mtlSnArr = this.mtlSnArr.filter(function (item) {
                return snArr.indexOf(item) == -1;
              });

              this.tableList[index].mpInvActivitySnHtWmsList = this.mpMtlSnHtWmsList;
              this.tableList[index].mtlQty = mtlQty;
              this.tableList[index].mtlSpuqty = this.mpMtlSnHtWmsList.length;
              this.tableList[index].oldQty = mtlQty;
              //可领-移料数量
              this.tableList[index].orderMaterialNeedQty =  this.changeNumberHt(orderMaterialNeedQty);



            })
            .catch(_ => {});
      }

    },



  },
  computed: {
    printDisable() {
      // return this.basicInfo.htWmsStatus==0|| !this.currentId;
      return this.basicInfo.htWmsStatus===0?true:false;
    },
    getDisabledItems() {
      let disableItems = [];
      disableItems = this.getDisabledItemsChange();
      console.log(disableItems,'disableItems');

      return disableItems;
    },

  },
  mounted() {
    this.$nextTick(() => {
      this.setTableHeight();
    });
    const debounceFn = _.throttle(this.setTableHeight, 100);
    window.addEventListener('resize', debounceFn);

  },
  beforeDestroy() {
    const debounceFn = _.throttle(this.setTableHeight, 100);
    window.removeEventListener('resize', debounceFn);
  },
  created() {
    this.$nextTick(() => {
      this.fetchHouseList();

      // this.getFactory()
      this.getDeptList();
      this.initInfo();
      this.setHeight();
      this.handleGetEnum();

    });
  },
};
